
Partial Class Case_CaseNotes
    Inherits System.Web.UI.UserControl

    Private Const caseNoteStatusId As Integer = 1
    Private Const caseNoteResolutionId As Integer = 1

    Protected participantId As Integer

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load

        Me.RespondButton.Visible = False
        ErrorLabel.Visible = False

        If Not Page.IsPostBack Then
            Me.CaseNotesGridView.Sort("DateModified", SortDirection.Descending)
        End If

        If Not UserAuthorization.HasInsertPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseNotes) Then
            Me.CaseNotesGridView.Columns(7).Visible = False
            Me.AddNoteButton.Visible = False
        End If

        If Not Page.IsPostBack Then
            If Request("spendingplandenyreason") IsNot Nothing Then
                StartSpendingPlanDeniedNote()
            End If
            If Request("unid") IsNot Nothing Then
                Me.CaseNotesListPanel.Visible = False
                ShowNoteFromNotification()
            End If
        End If

    End Sub

    Private Sub ShowNoteFromNotification()
        Dim userNotificationId As Integer = CInt(Request("unid"))
        Dim noteId As Integer = Cdm.DataCore.UserSecurity.UserNotification.RetrieveFileNoteIdFromUserNotification(userNotificationId)
        ViewNote(noteId, noteId)
    End Sub

    Protected Sub CaseNotesGridView_PageIndexChanging(ByVal sender As Object, _
                                                      ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) _
                                                      Handles CaseNotesGridView.PageIndexChanging

        Me.CaseNotesGridView.PageIndex = e.NewPageIndex
        Me.CaseNotesGridView.DataBind()
        Me.CaseNotesListPanel.Visible = True

    End Sub

    Protected Sub CaseNotesGridView_RowCommand(ByVal sender As Object, _
                                               ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
                                               Handles CaseNotesGridView.RowCommand

        ' Hide the initial list.
        Me.CaseNotesListPanel.Visible = False
        ' Set the hidden field with the CaseNoteId for use on the save operation.
        Me.CaseNoteIdHiddenField.Value = e.CommandArgument

        Select Case e.CommandName

            Case "View"

                ViewNote(Me.CaseNoteIdHiddenField.Value, e.CommandArgument)
                ' Get the parent case note.
                
                
            Case "Respond"

                SetUpResponse()
        End Select

    End Sub

    Private Sub ViewNote(ByVal noteId As Integer, ByVal noteid2 As Integer)
        Dim parentCaseNote As Cdm.DataCore.CaseNotes.CaseNoteDisplay = Cdm.DataCore.CaseNotes.CaseNoteDisplay.Retrieve(noteId)
        Me.ResponseListSubjectLabel.Text = parentCaseNote.Subject
        Me.ResponseListDateLabel.Text = parentCaseNote.DateModified.ToString
        Me.ResponseListFromLabel.Text = parentCaseNote.Role
        Me.ResponseListNoteLabel.Text = parentCaseNote.Note

        ' Transfer to a view of a specific note's responses.
        Me.TitleLabel.Text = "View Note(s)"
        ' Add the CaseNoteId parameter value to the object data source via the command argument
        ' of the link button located in the grid.
        If Me.ViewNoteObjectDataSource.SelectParameters.Count > 0 Then
            Me.ViewNoteObjectDataSource.SelectParameters.RemoveAt(0)
        End If
        Me.ViewNoteObjectDataSource.SelectParameters.Add("caseNoteId", noteid2)
        Me.ViewNoteObjectDataSource.Select()
        ' Perform a select and bind the repeater.
        Me.ViewResponsesRepeater.DataBind()
        Me.ViewNotePanel.Visible = True
        Me.RespondButton.Visible = UserAuthorization.HasInsertPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseNotes)

    End Sub

    Private Sub SetUpResponse()
        ' Transfer to a panel that allows a user to add a new response.
        Dim parentCaseNote As Cdm.DataCore.CaseNotes.CaseNoteDisplay = Cdm.DataCore.CaseNotes.CaseNoteDisplay.Retrieve(Me.CaseNoteIdHiddenField.Value)
        Me.ResponseSubjectLabel.Text = parentCaseNote.Subject
        Me.ResponseDateLabel.Text = parentCaseNote.DateModified.ToString
        Me.ResponseFromLabel.Text = parentCaseNote.Role
        Me.BindCaseNoteStatusDropDownList()
        Me.BindCaseNoteResolutionDropDownList(parentCaseNote.CaseNoteTypeId)
        Me.ResponseCaseNoteStatusDropDownList.SelectedValue = parentCaseNote.CaseNoteStatusId

        With Me.ResponseSendToCheckBoxList
            .DataSource = Cdm.DataCore.UserSecurity.Role.ListByNotificationType(CInt(Cdm.DataCore.CaseNotes.Notification.NotificationType.ResponseIsCreated))
            .DataTextField = "RoleDisplayName"
            .DataValueField = "RoleId"
            .DataBind()
            If .Items.Count = 0 Then
                Me.ResponseSendToEmtpyLabel.Visible = True
            End If
        End With

        Me.TitleLabel.Text = "Respond to This Note"
        Me.ResponsePanel.Visible = True
        Me.ResponseCaseNoteStatusDropDownList.Enabled = UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseNoteStatus)

    End Sub

    Protected Sub CaseNotesGridView_RowDataBound(ByVal sender As Object, _
                                                 ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
                                                 Handles CaseNotesGridView.RowDataBound

        ' Determine that we're in a datarow.
        If e.Row.RowType = DataControlRowType.DataRow Then

            ' Format the # of responses field.
            If CInt(e.Row.Cells(4).Text) > 0 Then
                e.Row.Cells(4).Text = "Available"
            Else
                e.Row.Cells(4).Text = "No"
            End If

            ' Format the last modified date to a short date string.
            If IsDate(e.Row.Cells(2).Text) Then
                e.Row.Cells(2).Text = CDate(e.Row.Cells(2).Text).ToShortDateString
            End If

        End If

    End Sub

    Protected Sub AddNoteButton_Click(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles AddNoteButton.Click

        Me.BindTypeDropDownList()

        With Me.SendToCheckBoxList
            .DataSource = Cdm.DataCore.UserSecurity.Role.ListByNotificationType(CInt(Cdm.DataCore.CaseNotes.Notification.NotificationType.NoteIsCreated))
            .DataTextField = "RoleDisplayName"
            .DataValueField = "RoleId"
            .DataBind()
            If .Items.Count = 0 Then
                Me.SendToEmptyLabel.Visible = True
            End If
        End With

        ' Switch to add new note mode.
        Me.CaseNotesListPanel.Visible = False
        Me.NewNotePanel.Visible = True
        Me.NoteTextBox.Text = ""
        Me.SubjectTextBox.Text = ""
        If Me.TypeDropDownList.Items.Count > 0 Then
            Me.TypeDropDownList.SelectedIndex = 0
        End If

    End Sub

    Private Sub StartSpendingPlanDeniedNote()

        Me.BindTypeDropDownList()

        With Me.SendToCheckBoxList
            .DataSource = Cdm.DataCore.UserSecurity.Role.ListByNotificationType(CInt(Cdm.DataCore.CaseNotes.Notification.NotificationType.NoteIsCreated))
            .DataTextField = "RoleDisplayName"
            .DataValueField = "RoleId"
            .DataBind()
            If .Items.Count = 0 Then
                Me.SendToEmptyLabel.Visible = True
            End If
        End With

        Dim denialReasonId As Integer = Convert.ToInt32(Request("spendingplandenyreason"))
        Dim defaultText As String = ""
        Dim denialReason As Cdm.DataCore.LookupTables.LuSpendingPlanDenialReason = _
                 Cdm.DataCore.LookupTables.LuSpendingPlanDenialReason.Retrieve(denialReasonId)
        If denialReason IsNot Nothing Then
            defaultText = denialReason.Description
        End If

        ' Switch to add new note mode.
        Me.CaseNotesListPanel.Visible = False
        Me.NewNotePanel.Visible = True
        Me.NoteTextBox.Text = "Spending plan has been denied:  " & defaultText
        Me.SubjectTextBox.Text = EntityController.GetSingleDisplayName("Spending Plan") & " Denied."
        If Me.TypeDropDownList.Items.Count > 0 Then
            SetTypeToGeneral()
        End If


    End Sub
    Private Sub SetTypeToGeneral()
        TypeDropDownList.Items.FindByText("General").Selected = True
    End Sub

    Protected Sub SaveNewNoteButton_Click(ByVal sender As Object, _
                                          ByVal e As System.EventArgs) _
                                          Handles SaveNewNoteButton.Click

        Dim tran As New Gentle.Framework.Transaction

        Try

            If Not ValidateEntries() Then Exit Sub

            ' Create a new instance of a case note.
            Dim newNote As New Cdm.DataCore.CaseNotes.CaseNote(CInt(Session("ParticipantId")), _
                                                               Nothing, _
                                                               Now.ToString, _
                                                               Now, _
                                                               Me.SubjectTextBox.Text, _
                                                               Me.NoteTextBox.Text, _
                                                               UserAuthorization.CurrentUser.Id, _
                                                               CInt(Me.TypeDropDownList.SelectedValue), _
                                                               caseNoteStatusId, _
                                                               caseNoteResolutionId)
            ' Save the newly created instance.
            newNote.Persist(tran)

            ' Get the list of selected roles and put them in a hash table for the notification
            ' send method.
            Dim roleList As New Hashtable
            For Each role As ListItem In Me.SendToCheckBoxList.Items
                If role.Selected Then
                    roleList.Add(Convert.ToInt32(role.Value), role.Text)
                End If
            Next

            ' Send the notification.
            Cdm.DataCore.CaseNotes.Notification.Send(Cdm.DataCore.CaseNotes.Notification.NotificationType.NoteIsCreated, _
                                                     EntityController.GetParticipant().ParticipantId, _
                                                     Application("EmailFromAddress"), _
                                                     Application("EmailServer"), _
                                                     Application("EmailFromDisplayName"), _
                                                     roleList, EntityController.ApplicationHomePage)
            If UserAuthorization.CurrentUser.RoleId.Equals(CInt(Cdm.DataCore.UserSecurity.Role.RoleType.Participant)) Then
                Cdm.DataCore.CaseNotes.Notification.Send(Cdm.DataCore.CaseNotes.Notification.NotificationType.ParticipantHasMadeNote, _
                                                    EntityController.GetParticipant().ParticipantId, _
                                                     Application("EmailFromAddress"), _
                                                     Application("EmailServer"), _
                                                     Application("EmailFromDisplayName"), _
                                                     roleList, EntityController.ApplicationHomePage)
            End If

            If IsHealthAndSafetyNote(newNote.CaseNoteTypeId) Then
                Cdm.DataCore.CaseNotes.Notification.Send(Cdm.DataCore.CaseNotes.Notification.NotificationType.HealthAndSafetyNoteDocumented, _
                                                    EntityController.GetParticipant().ParticipantId, _
                                                     Application("EmailFromAddress"), _
                                                     Application("EmailServer"), _
                                                     Application("EmailFromDisplayName"), _
                                                     roleList, EntityController.ApplicationHomePage)
            End If
            tran.Commit()

        Catch gentleEx As Gentle.Common.GentleException

            tran.Rollback()

        Catch ex As Exception

            tran.Rollback()
            Throw ex

        End Try

        ' Since the save was successful revert back to the list view.
        Me.CaseNotesListPanel.Visible = True
        Me.NewNotePanel.Visible = False
        Me.TypeDropDownList.SelectedIndex = 0
        Me.NoteTextBox.Text = ""
        Me.TitleLabel.Text = "Notes"

        Me.NotesObjectDataSource.Select()
        Me.CaseNotesGridView.DataBind()

    End Sub
    Private Function ValidateEntries() As Boolean
        Dim errorMessage As String = ""

        If TypeDropDownList.SelectedValue.Equals("") Then
            errorMessage = "Please select a message type."
        End If
        If TypeDropDownList.Items.Count = 0 Then
            errorMessage = "You do not have permissions to send notes.  Please contact your administrator."
        End If

        If NoteTextBox.Text.Equals("") Then
            errorMessage = "Please enter a Note."
        End If

        If SubjectTextBox.Text.Equals("") Then
            errorMessage = "Please enter a Subject."
        End If

        If errorMessage.Equals("") Then
            Return True
        Else
            ErrorLabel.Visible = True
            ErrorLabel.Text = errorMessage
            Return False
        End If

    End Function


    ''' <summary>
    ''' Checks if the current note is a health and safety note type.
    ''' </summary>
    ''' <param name="noteTypeId">The Id of the current note type</param>
    ''' <returns>true if the description matching the Id is health and safety.</returns>
    ''' <remarks></remarks>
    Private Function IsHealthAndSafetyNote(ByVal noteTypeId As Integer) As Boolean
        Try
            Dim noteType As Cdm.DataCore.LookupTables.LuCaseNoteType = Cdm.DataCore.LookupTables.LuCaseNoteType.Retrieve(noteTypeId)
            If noteType.Description.ToUpper().Equals("HEALTH AND SAFETY") Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Return False
        End Try
    End Function

    Protected Sub CancelNewNoteButton_Click(ByVal sender As Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles CancelNewNoteButton.Click

        ' Revert back to the list view.
        Me.CaseNotesListPanel.Visible = True
        Me.NewNotePanel.Visible = False
        Me.TypeDropDownList.SelectedIndex = 0
        Me.NoteTextBox.Text = ""
        Me.SubjectTextBox.Text = ""
        Me.TitleLabel.Text = "Notes"

    End Sub

    Protected Sub SaveResponseButton_Click(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles SaveResponseButton.Click

        Dim tran As New Gentle.Framework.Transaction

        Try

            ' Save case note status id.
            Dim note As Cdm.DataCore.CaseNotes.CaseNote = Cdm.DataCore.CaseNotes.CaseNote.Retrieve(CInt(Me.CaseNoteIdHiddenField.Value))
            note.CaseNoteStatusId = Me.ResponseCaseNoteStatusDropDownList.SelectedValue
            note.CaseNoteResolutionId = Me.ResponseResolutionTypeDropDownList.SelectedValue
            note.Persist(tran)

            ' Create a new instance of a case note response.
            Dim resp As New Cdm.DataCore.CaseNotes.CaseNoteResponse(Me.CaseNoteIdHiddenField.Value, _
                                                                    Now.ToShortDateString, _
                                                                    Now, _
                                                                    UserAuthorization.CurrentUser.Id, _
                                                                    Me.ResponseTextBox.Text)
            ' Save the new case note response.
            resp.Persist(tran)

            ' Get the list of selected roles and put them in a hash table for the notification
            ' send method.
            Dim roleList As New Hashtable
            For Each role As ListItem In Me.ResponseSendToCheckBoxList.Items
                If role.Selected Then
                    roleList.Add(Convert.ToInt32(role.Value), role.Text)
                End If
            Next

            ' Send a notification.
            Cdm.DataCore.CaseNotes.Notification.Send(Cdm.DataCore.CaseNotes.Notification.NotificationType.ResponseIsCreated, _
                                                     EntityController.GetParticipant.ParticipantId, _
                                                     Application("FromEmailAddress"), _
                                                     Application("EmailServer"), _
                                                     Application("EmailFromDisplayName"), _
                                                     roleList, EntityController.ApplicationHomePage)

            If UserAuthorization.CurrentUser.RoleId.Equals(CInt(Cdm.DataCore.UserSecurity.Role.RoleType.Participant)) Then
                Cdm.DataCore.CaseNotes.Notification.Send(Cdm.DataCore.CaseNotes.Notification.NotificationType.ParticipantHasMadeNote, _
                                                    EntityController.GetParticipant().ParticipantId, _
                                                     Application("EmailFromAddress"), _
                                                     Application("EmailServer"), _
                                                     Application("EmailFromDisplayName"), _
                                                     roleList, EntityController.ApplicationHomePage)
            End If

            If IsHealthAndSafetyNote(CInt(Me.CaseNoteIdHiddenField.Value)) Then
                Cdm.DataCore.CaseNotes.Notification.Send(Cdm.DataCore.CaseNotes.Notification.NotificationType.HealthAndSafetyNoteDocumented, _
                                                    EntityController.GetParticipant().ParticipantId, _
                                                     Application("EmailFromAddress"), _
                                                     Application("EmailServer"), _
                                                     Application("EmailFromDisplayName"), _
                                                     roleList, EntityController.ApplicationHomePage)
            End If



            tran.Commit()

        Catch gentileEx As Gentle.Common.GentleException

            tran.Rollback()

        Catch ex As Exception

            tran.Rollback()
            Throw ex

        End Try

        ' Revert back to the list view.
        Me.ResponsePanel.Visible = False
        Me.CaseNotesListPanel.Visible = True
        Me.ResponseTextBox.Text = ""
        Me.NotesObjectDataSource.Select()
        Me.CaseNotesGridView.DataBind()
        Me.TitleLabel.Text = "Notes"

    End Sub

    Protected Sub CancelResponseButton_Click(ByVal sender As Object, _
                                             ByVal e As System.EventArgs) _
                                             Handles CancelResponseButton.Click

        ' Revert back to the list view.
        Me.ResponsePanel.Visible = False
        Me.CaseNotesListPanel.Visible = True
        Me.ResponseTextBox.Text = ""
        Me.TitleLabel.Text = "Notes"

    End Sub

    Protected Sub BackToListButton_Click(ByVal sender As Object, _
                                         ByVal e As System.EventArgs) _
                                         Handles BackToListButton.Click

        ' Revert back to the list view.
        Me.ViewNotePanel.Visible = False
        Me.CaseNotesListPanel.Visible = True
        Me.TitleLabel.Text = "Notes"

    End Sub

    Protected Sub RespondButton_Click(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles RespondButton.Click

        ' Transfer to a panel that allows a user to add a new response.
        SetUpResponse()
        Me.ViewNotePanel.Visible = False

    End Sub

    Protected Sub CaseNotesGridView_Sorting(ByVal sender As Object, _
                                            ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) _
                                            Handles CaseNotesGridView.Sorting

        Me.CaseNotesListPanel.Visible = True

    End Sub

    Protected Sub BindTypeDropDownList()

        ' Bind the drop down list that allows selection of case note type.
        With Me.TypeDropDownList
            .DataSource = Cdm.DataCore.LookupTables.LuCaseNoteType.ListByRoleID(UserAuthorization.CurrentUser.RoleId)
            .DataTextField = "Description"
            .DataValueField = "CaseNoteTypeId"
            .DataBind()
        End With

    End Sub

    Protected Sub BindCaseNoteStatusDropDownList()

        With Me.ResponseCaseNoteStatusDropDownList
            .DataSource = Cdm.DataCore.LookupTables.LuCaseNoteStatus.ListAll
            .DataTextField = "Description"
            .DataValueField = "CaseNoteStatusId"
            .DataBind()
        End With

    End Sub

    Protected Sub BindCaseNoteResolutionDropDownList(ByVal caseNoteTypeId As Integer)

        With Me.ResponseResolutionTypeDropDownList
            .DataSource = Cdm.DataCore.LookupTables.LuCaseNoteResolution.ListByCaseNoteTypeId(caseNoteTypeId)
            .DataTextField = "Description"
            .DataValueField = "CaseNoteResolutionId"
            .DataBind()
        End With

    End Sub

End Class